/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 * @author Sergey I. Salishev
 */
package org.apache.cgiservlet;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import org.python.antlr.base.mod;
import org.python.compiler.Module;
import org.python.core.BytecodeLoader;
import org.python.core.CompilerFlags;
import org.python.core.Options;
import org.python.core.ParserFacade;
import org.python.core.Py;
import org.python.core.PyCode;
import org.python.core.PyDictionary;
import org.python.core.PyFile;
import org.python.core.PyList;
import org.python.core.PyObject;
import org.python.core.PyRunnable;
import org.python.core.PyString;
import org.python.core.PySystemState;
import org.python.core.imp;
import org.python.core.io.StreamIO;
import org.python.core.packagecache.SysPackageManager;

/**
 * Jython CGI servlet
 */
public class PythonServlet extends CGIServlet {

	private static final long serialVersionUID = 1L;

	private final HashMap<File, Class<?>> classCache = new HashMap<File, Class<?>>(1);
	private ThreadLocal<File> script = new ThreadLocal<File>();

	private synchronized Class<?> getScriptClass(File scriptFile) throws IOException {
		Class<?> res = classCache.get(scriptFile);
		if (res == null) {
			res = makeClass(new FileInputStream(scriptFile), scriptFile
					.getPath(), "exec");
			classCache.put(scriptFile, res);
		}
		return res;
	}
	
	public static Class<?> makeClass(InputStream istream, String filename, String kind) {
        CompilerFlags cflags = new CompilerFlags();
		mod node = ParserFacade.parse(istream, kind, filename, cflags);
		String name = Py.getName();
		try {
		    ByteArrayOutputStream ostream = new ByteArrayOutputStream();
		    Module.compile(node, ostream, name, filename, true, kind.equals("single"), cflags);
		
		    return BytecodeLoader.makeClass(name, ostream.toByteArray());
		} catch (Throwable t) {
		    throw ParserFacade.fixParseError(null, t, filename);
		}
    }	

	@Override
	protected void runScript() throws IOException {
		File scriptFile = script.get();
		Class<?> scriptClass = getScriptClass(scriptFile);
		
		PyCode code;
		
		try {
            Object o = scriptClass.getConstructor(new Class[] {String.class})
                    .newInstance(new Object[] {scriptFile.getPath()});
            code = ((PyRunnable)o).getMain();
        } catch (Exception e) {
        	throw new RuntimeException(e);
        }
		
		imp.createFromCode("__main__", code, scriptFile.getAbsolutePath());
	}

	@Override
	protected void prepareScript(final String[] args,
			final Map<String, String> env, final InputStream in,
			final OutputStream out, final File scriptFile) throws IOException {
		
		script.set(scriptFile);

		PySystemState state = new PySystemState();
		
		Py.setSystemState(state);
				
		String dir = scriptFile.getParentFile().getAbsolutePath();
		state.setCurrentWorkingDir(dir);
		
		state.path.add(new PyString(dir));
		
		state.executable = new PyString("python");
		
		initArgv(state, args);

		initEnviron(state, env);

		initStreams(state, in, out);
		
		state.setClassLoader(new ClassLoader(PythonServlet.class.getClassLoader()) {

			@Override
			protected synchronized Class<?> loadClass(String name,
					boolean resolve) throws ClassNotFoundException {
				
				if (name.startsWith("org") || name.startsWith("java")) {
					return super.loadClass(name, resolve);
				}
				throw new ClassNotFoundException("dont' load java");
			}
			
		});
	}

	private void initStreams(PySystemState state, final InputStream in,
			final OutputStream out) {
		String mode = Options.unbuffered ? "b" : "";
		int buffering = Options.unbuffered ? 0 : 1;

		state.__stdout__ = state.stdout = new PyFile(new StreamIO(out, false),
				"<stdout>", "w" + mode, buffering);
		state.__stdin__ = state.stdin = new PyFile(new StreamIO(in, false),
				"<stdin>", "r" + mode, buffering);
	}

	private void initEnviron(PySystemState state, Map<String, String> env) {
		PyDictionary environ = (PyDictionary) state.getEnviron();
		environ.clear();

		for (String key : env.keySet()) {
			environ.__setitem__(Py.newString(key), Py.newString(env.get(key)));
		}
	}

	private static void initArgv(PySystemState state, String[] args) {
		PyList argv = new PyList();
		if (args != null) {
			for (String arg : args) {
				argv.append(new PyString(arg));
			}
		}
		state.argv = argv;
	}

}
